﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.Reflection;
using FoundationLib.Web.Mvc.DataAnnotation;

namespace FoundationLib.Web.Mvc
{
	public static class RangeStyleHelper
	{
		public static string RangeStyleFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> property, string defaultCss)
		{
			MemberExpression memberExpression = property.Body as MemberExpression;
			if (memberExpression == null)
				throw new ArgumentException("Expression is not a property.", "property");

			MemberInfo info = memberExpression.Member;
			if (!info.MemberType.HasFlag(MemberTypes.Property))
				throw new ArgumentException("Expression is not a property.", "property");

			object value = null;
			try
			{
				value = property.Compile().Invoke(helper.ViewData.Model);
			}
			catch (Exception)
			{
				return defaultCss;
			}

			IEnumerable<RangeStyleAttribute> attributes = info.GetCustomAttributes(typeof(RangeStyleAttribute), true)
				.Cast<RangeStyleAttribute>();

			string style = null;
			foreach (RangeStyleAttribute attribute in attributes)
			{
				if (attribute.Test(value, out style))
					break;
			}

			if (style == null)
				style = defaultCss;

			return style;
		}

		public static string RangeStyleFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> property)
		{
			return (RangeStyleFor(helper, property, null));
		}
	}
}
